/* Import required JavaScript libraries */
dojo.require("dojo._base.array");
dojo.require("dojo.json");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.form.Form");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.Toolbar");
dojo.require("dijit.Tree");
dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.require("esri.map");
dojo.require("esri.dijit.Scalebar");
dojo.require("esri.dijit.Legend");
if (user_device == 'mobile' || user_device == 'tablet') {
    dojo.require("esri.dijit.PopupMobile");
}
else {
    dojo.require("esri.dijit.Popup");
}
dojo.require("esri.dijit.InfoWindow");
dojo.require("dojo.data.ItemFileReadStore"); // Needed by Search
dojo.require("dijit.form.FilteringSelect"); // Needed by Search
dojo.require("esri.tasks.query"); // Needed by Parking Infowindows
dojo.require("esri.layers.KMLLayer"); // Needed to support KML layers
    
/* Define Global Variables */
var map;
var layers = new Array();  	//Holds the initialized layers.
var layersActive = new Array();	//Holds the visible layers.

var legendLayers = new Array();	//Holds active layers for legend
var legend = new Array();       //Legend Object

var benchmark = [];
benchmark['startTime'] = new Date().getTime();

/* Function init() starts when dojo is loaded */
function init() {
	
	campusExtent = new esri.geometry.Extent({xmin: -13342700,ymin: 4084100,	xmax: -13339988, ymax: 4084700,spatialReference:{wkid:102100}});
	
        if (user_device == 'mobile'  || user_device == 'tablet') {
            var popup = new esri.dijit.PopupMobile(null, dojo.create("div"));
            
            //Start Geolocation if on Mobile or tablet.

        }
        else {
            var popup = new esri.dijit.Popup(null, dojo.create("div"));
        }
	map = new esri.Map("mapDiv", { 
		extent: campusExtent,
		infoWindow: popup
	});
	var scalebar = new esri.dijit.Scalebar({
	  map:map,
	  attachTo:"bottom-left"
	});
	
	dojo.connect(map,"onUpdateEnd",hideLoading);
	dojo.connect(map,"onUpdateStart",showLoading);
	
	initLegend();
	initLayerLoader();
	//initRoomBuildingFinder();
		
	ddtreemenu.createTree("layersmenu", true);
	
	

	/* When map loads, run these commands */
	dojo.connect(map, 'onLoad', function(theMap) {		
		//Once the map has loaded, initialize the onClick-Parking infowindows
		initParkingPopup();
		
		//Once the map has loaded, init the onClick-Building infowindows
		initBuildingPopup();
		
		//Once the map has loaded, init the Print Module
		initPrintModule();
		
		//Once the map has loaded, init the Search Module (version 2)
		initSearchModule_v2();	
                
                initGeolocation(map);
		
			
		//resize the map when the browser resizes
		dojo.connect(dijit.byId('mapDiv'), 'resize', map,map.resize);
		
		//update extent on certain page elements when extent is changed
		//This includes the Share Link box and scale indicator.
		dojo.connect(map, "onExtentChange", onMapExtentChange);
		
		document.getElementById("info").value = mapRootUrl;
		
		//Update the Map Extent once the page and map have been loaded. 
		onMapExtentChange(map.extent, map._delta, '', map.__LOD);
                
                if (user_device == 'mobile') {
                    window.toggleSidebar();
                }
                //Once the map has loaded and added the basemap, check to see if the user is using any parameters from a shared link
		initShareLink();
		
	}); //end of dojo.connect(map, 'onLoad');
  	

} // End of init();


dojo.addOnLoad(init);


///////////////////////////////////////////
/*      Functions and Includes           */
///////////////////////////////////////////

function hideLoading() {
	benchmark['startTime'] = new Date().getTime();
	document.getElementById('loadingImg').style.display = 'none';
}
function showLoading() {
	document.getElementById('loadingImg').style.display = 'block';
	benchmark['endTime'] = new Date().getTime();
	console.log('Load Time: '+(benchmark['endTime'] - benchmark['startTime'])+'ms.');
}
function addLayer(layer) {
	if(typeof layers[layer] == 'undefined' || typeof layers[layer].loaded != 'boolean') {
		if (typeof layersConfig[layer] == 'undefined') {
			console.log(layer + ' was not included in the default layers config.  Will attempt to load it dynamically.');
			dojo.xhrGet({
			    // The URL to request
			    url: "/data/layers.json.php?layers="+layer,
			    handleAs: "json",
			    // The method that handles the request's successful result
			    // Handle the response any way you'd like!
			    sync: true,
			    load: gotLayersJSON
			});
		}
		layers[layer] = initJSONLayer(layersConfig[layer]);
	}
	if (dojo.indexOf(layersActive,layer) == -1) { // check if layer is already active.
			map.addLayers([layers[layer]]);
			
			if (layers[layer].id != 'basemap') {
				if (layers[layer].id == 'SBMTD' || layers[layer].id == 'webcams') {
					layers['esriBasemapCanvas'] = new esri.layers.ArcGISDynamicMapServiceLayer('http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer', {id:'esriBasemapCanvas'});
					layers['esriBasemapCanvasRef'] = new esri.layers.ArcGISDynamicMapServiceLayer('http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer', {id:'esriBasemapCanvas'}); 
					console.log('Adding ESRI Grey Basemap');
					map.addLayer(layers['esriBasemapCanvas'], 0);
					console.log('Adding ESRI Grey Basemap Reference');
					map.addLayer(layers['esriBasemapCanvasRef'],1);
				}
				legendLayers.push({layer:layers[layer], title:' '});
			}
			else {
				map.addLayer(layers[layer]);
			}
			//map.addLayers([layers[layer]]);
			layers[layer].setVisibility(true);
			if (layersConfig[layer].infowindow != null) {
				//layersConfig[layer].infowindow = dojo.json.parse(layersConfig[layer].infowindow);
				
				var count = 0;
				dojo.forEach(layersConfig[layer].infowindow, function(iw){
					initLayerPopup(layer, count);
					count++;
				});
			}
			console.log('Activated "'+layers[layer].id+'".');
			//Adds the newly active layer id to the top of the activeLayers array
			layersActive.unshift(layers[layer].id);
	}
	else {
		console.log('Layer "'+layer+'" already active.');
	}
	updateShareLink();
	
	dojo.connect(layers[layer], "onResume", function(result) { 
		if (layersConfig[layer].zoomOnLoad == 1) {
				map.setExtent(layers[layer].fullExtent.expand(1.5));	
		}
                if (layersConfig[layer].zoomOnLoad == 2) {
				map.setExtent(campusExtent);
		}
		if (typeof layersConfig[layer].mapOverlay != null && layersConfig[layer].mapOverlay != '') {
			//alert('Setting Map Overlay');
			dojo.byId('mapOverlayDiv').style.visibility = 'visible';
			dojo.byId('mapOverlayDiv').innerHTML = layersConfig[layer].mapOverlay;	
		}
		else {
			dojo.byId('mapOverlayDiv').style.display = 'hidden';
			dojo.byId('mapOverlayDiv').innerHTML = '';
		}
		if (layersConfig[layer].openLegendOnLoad == 1) {
			dijit.byId('mainAccordionCont').selectChild(dijit.byId('pane_Legend'));
		}
		if (legend._started) {
			legend.refresh();	
		}
	});
}
function clearLayers() {
	dojo.byId('mapOverlayDiv').innerHTML = '';
	dojo.byId('mapOverlayDiv').style.visibility = 'hidden';
	if (layersActive.length > 0) {  //if there are active layers, start the loop
		dojo.forEach(layersActive, function(layer) {
			//Prevent the basemap from being disabled.
			if (layers[layer].id != 'basemap') {
				layers[layer].setVisibility(false);	
				if (infowindowGraphicsLayer[layer]) {
					infowindowGraphicsLayer[layer].clear();
				}
			}
		});
		layersActive = [];
		legendLayers.length = 0;  //Reset the legendLayers array so that the legend doesn't add duplicate entries.'
	}
	if (layers['esriBasemapCanvas'] || layers['esriBasemapCanvasRef']) {
		map.removeLayer(layers['esriBasemapCanvas']);
		map.removeLayer(layers['esriBasemapCanvasRef']);
	}
        if (typeof searchresultGraphicLayer === 'object') {
            map.removeLayer(searchresultGraphicLayer);
            //setTimeout(map.addLayer(searchresultGraphicLayer),1000);
        }
	if (legend._started) {
		legend.refresh();	
	}
        searchResultClicked = '';
}
function changeLayer(layer) {
	//if (typeof layers[layer] == undefined) {
		//console.log('Layer not initialized.  Loading layer: '+layer);
	//	alert('First time initializing layer..............');
	//}
	if (dojo.indexOf(layersActive,layer) == -1 || layer === 'customlayer') {
		clearLayers();
		setTimeout(addLayer(layer), 1000);
		 
		//console.log('Zooming to layer extent: '+layers[layer].initialExtent);
		//map.setExtent(layers[layer].fullExtent);
                dojo.xhrPost({
                    url: "/api.php",
                    content: {
                      action: "layerLoaded",
                        layer: layer
                    }
                });
	}
	else {
		console.log('Layer "'+layers[layer].id+'" already active.');
	}
	if (legend._started) {
		legend.refresh();	
	}
}
function initLegend() {
	dojo.connect(map,'onLayersAddResult',function(results){
	  if (legend._started) {
	  	legend.refresh();
	  }
	  else {	  	
		  legend = new esri.dijit.Legend({
		    map:map,
		    layerInfos: legendLayers,
		    respectCurrentMapScale:true
		  },"legendDiv");
		  legend.startup();
		  console.log('Legend module started.');
	  }

	});
}
function orientationChanged() {
	if(map) {
        map.reposition();
    	map.resize();
	}
}
function cleanArray(actual){
  var newArray = new Array();
  for(var i = 0; i<actual.length; i++){
      if (actual[i]){
        newArray.push(actual[i]);
    }
  }
  return newArray;
}
function getLayerIDbyName(layer,layer_name) {
    var r = '';
    dojo.forEach(layers[layer].layerInfos, function(lyr){
        if (lyr.name == layer_name) {
           r=lyr.id;
        }
    });
    return r;
}
function updateShareLink() {
     var extent = map.extent;
     // This needs to be moved to it's own module.
     var s= "";
     var str = [];
     var alayers = '';
     var search_result = '';
     var current_extent = '';
     if (typeof layersActive != 'undefined' && layersActive[0] != '' && layersActive[0] != 'basemap' && typeof layersActive[0] != 'undefined' && dojo.byId(sharelinkCurrentLayer).checked == true) {
             alayers = 'activelayer='+layersActive[0];
             str.push(alayers);
     }
     if (typeof searchResultClicked != 'undefined' && searchResultClicked != '' && dojo.byId(sharelinkSearchResult).checked == true) {
             //delete searchResultClicked.geometry;
             var sr = dojo.clone(searchResultClicked);
             //delete sr.geometry;
             delete sr.searchScore;
             search_result = 'searchResult='+dojo.json.stringify(sr);
             str.push(search_result);
     }
     if (dojo.byId(sharelinkExactExtent).checked == true) {
         current_extent = "xmin=" + extent.xmin.toFixed(0) + "&ymin=" + extent.ymin.toFixed(0) + "&xmax=" + extent.xmax.toFixed(0) + "&ymax=" + extent.ymax.toFixed(0);
         str.push(current_extent);
     }
     s=mapRootUrl;
     if (typeof str[0] !== 'undefined') {
         s=s+"?"+ str.join('&');	
     }
     
    console.log('Updating share link..');
    //alert('Updating!');
    document.getElementById("info").value = s;
     shareLink = s;
}
// ON MAP EXTENT CHANGE
function onMapExtentChange(extent, delta, levelChange, lod){
	//var scale = dojo.number.format(lod.scale, {
	//	places: 0
	//});
	//dojo.byId('mapScale').innerHTML = dojo.string.substitute("1 : ${0}", [scale]);
	if (sharelinkDialog.open == false) {
            updateShareLink();
        }
	console.log('Extent updated in share link.');
        
        if (lod.scale <= 2000 && dojo.byId("floorSelectorDiv").style.display != 'block') {
            dojo.byId("floorSelectorDiv").style.display='block';
            console.log("Displaying the floor selector.");
        }
        else if (lod.scale > 2000 && dojo.byId("floorSelectorDiv").style.display != 'none') {
            dojo.byId("floorSelectorDiv").style.display='none';
            console.log("Hiding the floor selector.");
        }
}
function SelectAll(id) {
	document.getElementById(id).focus();
	document.getElementById(id).select();
}
function parseGeometry(result_geometry) {
    var geometry = '';
    result_geometry = eval(result_geometry);
    if (result_geometry[0].length > 1) {
        var geometry = new esri.geometry.Polygon(new esri.SpatialReference({wkid:102100})); 
        geometry.addRing(result_geometry[0]);
    }
    else {
        if ((typeof result_geometry[0]['x'] === 'number') && (typeof result_geometry[0]['y'] === 'number')) {
            var geometry = new esri.geometry.Point([result_geometry[0]['x'],result_geometry[0]['y']],new esri.SpatialReference({wkid:102100}));        }
    }

    return geometry;
}